﻿//服务器两端用户的交互命令
var eCmd_RequestControl = 0;
var eCmd_AnswerControlRequest = 1;
var eCmd_ControlRequest_PwdWrong = 2;
var eCmd_StopControl = 3;
var eCmd_StopControlForLocalFailed = 4;

//远程交互时需要的信息
var checkStatusInterval = -1;
var localPassword = '';	
var checkOfflineTimes = 0;
var echoLoopId = null;
var checkLoopId = null;
var myuserid = '';
var remotingPeerId = '';
var socket = null;

//初始化webteamviewer 
function InitWebTeamViewer()
{
	if(remoteControl != null)
	{
		return;
	}
	remoteControl = new NiuniuRemoteControl();
	remoteControl.PluginLoaded = OnPluginLoadedCallback;
	remoteControl.PluginUnload = OnPluginUnload;
	remoteControl.doShowDownload = ShowDownload;
	remoteControl.OnControlNotice = OnControlNotice;	
	remoteControl.Init();
}

function appendInfo(info)
{
	$("#recvcontent").append("<br/><span>" + info + "</span>");
}

function StartEngine()
{
	remoteControl.StartEngine();
}

function ShowDownload(forceDownload)
{
	if(!forceDownload)
	{
		$('#controlstate').html('如果超过5秒无响应，请点此<a target="_blank" href="' + remoteControl.downloadUrl + '">安装</a>');
	}
	else{
		$('#controlstate').html('控件加载失败，你需要安装插件并启动，点此<a target="_blank" href="' + remoteControl.downloadUrl + '">安装</a>');
	}
}

function OnControlNotice(obj)
{
	$("#recvcontent").append("<br/><span>" + obj.param + "</span>");
}
	
function OnPluginUnload()
{
	clearInterval(checkStatusInterval);	
	$('#controlstate').html('控件连接断开，请<a onclick="StartEngine();" href="javascript:void(0);">点此启动</a>');
	$('#status').html("控件连接断开。");
	if(socket != null)
	{
		socket.emit("command", {type: eCmd_StopControlForLocalFailed, peerid:myuserid, userid:remotingPeerId});
	}
}

function OnPluginLoadedCallback(success)
{
	if(success)
	{
		//隐藏部分弹出的安装下载提示信息 
		$('#status').html("");
		$('#controlstate').html('远程组件加载成功，正在连接服务器，请稍候...');			
		$("#myid").val(myuserid);
		connectServer();
		setTimeout("GetVersion();", 300);
	}
	else
	{
		$('#controlstate').html('远程组件加载失败，<a onclick="StartEngine();" href="javascript:void(0);">点此启动</a>');
	}
}


function GetStatus()
{
	remoteControl.GetStatus( function(obj){
		var nStatus = obj.retValue;		
		var LIMIT_VALUE_STATUS = 100000;
		var connectStatus = parseInt(nStatus / LIMIT_VALUE_STATUS);
		var remoteStatus = parseInt(nStatus % LIMIT_VALUE_STATUS);
		var statusInfo = "连接状态：" + remoteControl.GetConnectStatusString(connectStatus) + "，远程状态：" + remoteControl.GetRemoteStatusString(remoteStatus);
		$('#status').html(statusInfo);
	} );
}

function GetVersion()
{
	remoteControl.GetVersion( function(obj){
		var verObj = eval("(" + obj.param + ")");
		//可以在此根据最新的版本号与控件返回的版本号对比，决定是否要提示升级  
		$('#versioninfo').html("控件版本号：" + verObj.version);		
	} );
}

function getPassword(len) 
{
	var chars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
	var res = "";
	for(var i = 0; i < len ; i ++) {
		var id = Math.ceil(Math.random()*51);
		res += chars[id];
	}
	return res;
}
	
function loopEcho()
{
	try
	{
		//console.log("loopEcho");
	}
	catch(e){}
	if(socket == null)
	{
		return;
	}
	socket.emit("echo", {userid:myuserid});
}

//远程过程中检查对方是否已经掉线 
function startOrStopCheckLoop(isStart)
{
	if(!isStart)
	{
		if(checkLoopId != null)
		{
			clearInterval(checkLoopId);
			checkLoopId = null;
		}
		checkOfflineTimes = 0;
		remotingPeerId = '';
	}
	else
	{
		checkLoopId = setInterval("doCheck();", 2000);
	}
}

function doCheck()
{
	if(socket != null)
	{
		socket.emit("check", {userid:remotingPeerId});
	}
}
	

function connectServer()
{
	//$("#btnInitRemote").hide();
	socket=io.connect('ggniu.cn:8888');
	//socket.emit('check', {userid: $('#peerid').val()});		
	socket.on('connect', function () {
		appendInfo("接连服务器成功.");
	});
	//接收来自服务端的信息事件c_hi
	socket.on('callback',function(msg)
	{
		//alert(msg);
		if(msg.type == 'reg')
		{
			myuserid = msg.userid;
			$("#myid").val(msg.userid);
			setCookie("myuserid", msg.userid);
			if(localPassword == '')
			{
				localPassword = getPassword(6);
				$("#mypassword").val(localPassword);
			}
			$('#controlstate').html('登录服务器成功，请输入对方ID进行远程，或告知对方您的ID以便对方可远程您的电脑。');
			appendInfo("登录成功.");
			if(echoLoopId != null)
			{
				clearInterval(echoLoopId);
			}
			echoLoopId = setInterval('loopEcho();', 1000);
		}
		else if(msg.type == 'connect')
		{
			socket.emit('reg', {userid:myuserid});
		}
		else if(msg.type == 'check')
		{
			if(!msg.exist)
			{
				checkOfflineTimes++;
				if(checkOfflineTimes > 3)
				{
					startOrStopCheckLoop(false);
					appendInfo("对方已经退出，结束远程.");
					remoteControl.DisConnect();
				}
			}
		}
		else if(msg.type == "echo")
		{
			try
			{
				//console.log("received echo ret.");
			}
			catch(e){}
		}
		else if(msg.type == 'command')
		{
			if(!msg.result)
			{
				appendInfo("命令发送失败，对方不在线.");
			}
		}
	});
	
	socket.on('command',function(msg){
		switch(msg.type)
		{
			case eCmd_RequestControl:
			{
				appendInfo("收到远程连接请求.");
				var peerid = msg.peerid;
				if(msg.password != localPassword)
				{
					appendInfo("对方请求的密码错误，拒绝远程.");
					socket.emit("command", {type: eCmd_ControlRequest_PwdWrong, peerid:myuserid, userid:peerid});
					return;
				}
				
				var ret = remoteControl.InitRemote($("#myid").val(), peerid, "孙悟空", "牛魔王");
				if(ret == emcontrolSuccess)
				{	
					clearInterval(checkStatusInterval);			
					checkStatusInterval = setInterval("GetStatus();", 1000);
				}
				remoteControl.StartControl(0, 0, 0);
				socket.emit("command", {type: eCmd_AnswerControlRequest, peerid:myuserid, userid:peerid});					
				appendInfo("正在启动远程服务.");
				remotingPeerId = msg.peerid;
				startOrStopCheckLoop(true);
			}
			break;
			case eCmd_AnswerControlRequest:
			{
				var peerid = msg.peerid;
				var ret = remoteControl.InitRemote($("#myid").val(), peerid, "孙悟空", "牛魔王");
				if(ret == emcontrolSuccess)
				{					
					clearInterval(checkStatusInterval);			
					checkStatusInterval = setInterval("GetStatus();", 1000);
				}
				remoteControl.StartControl(1, 1, 1);
				appendInfo("收到对方响应，正在启动远程，请稍候.");
				remotingPeerId = msg.peerid;
				startOrStopCheckLoop(true);
			}
			break;
			case eCmd_ControlRequest_PwdWrong:
			{
				appendInfo("密码错误，请输入正确的远程密码.");
			}
			break;
			case eCmd_StopControlForLocalFailed:
			{
				appendInfo("对方远程出错，结束远程.");
				remoteControl.DisConnect();
				startOrStopCheckLoop(false);
			}
			break;
			case eCmd_StopControl:
			{
				appendInfo("收到结束指令，退出远程.");
				remoteControl.DisConnect();
				startOrStopCheckLoop(false);
			}
			break;
		}
	});
}
	